﻿using JsonConversion;
using Newtonsoft.Json;
using RTracker.Models.Common;
using RTracker.Areas.Recruitment.Models.Candidate;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Script.Serialization;
using RTracker.Areas.Recruitment.Models.VacancyExpirence;
using RTracker.Areas.Recruitment.Models.CandidateSource;
using RTracker.Areas.Recruitment.Models.Department;

namespace RTracker.Areas.Recruitment.Controllers
{
    public class CandidateController : RTracker.Controllers.AppBaseController
    {
        //
        // GET: /Candidate/

        [HttpPost]
        public ActionResult Save(GCandidate oGCandidate)
        {

            try
            {
                //check if Model validation is true if not then return detail view with errors
                if (true)//ModelState.IsValid
                {
                    //call CheckSession to get session status
                    string SessionState = CheckSessionState();
                    //check if session state is ok else return false status to view.
                    if (SessionState == CAppConstants.SessionSuccess)
                    {
                        bool _userPermission = false;

                        if (oGCandidate.Candidate.OrganizationId == 0)
                        {
                            _userPermission = checkUserPermission(CUserPermissionsConstants.OrganizationCreate);
                        }
                        else
                        {
                            _userPermission = checkUserPermission(CUserPermissionsConstants.OrganizationUpdate);
                        }


                        if (_userPermission)
                        {
                            CCandidate objCCandidate = new CCandidate();
                            objCCandidate = oGCandidate.Candidate;
                            MCandidate objMCandidate = new MCandidate();

                            if (objCCandidate.CandidateId == 0)
                            {
                                objCCandidate.OrganizationId = CurrentUserSession.OrganizationId;
                                oGCandidate.Status = objMCandidate.CreateCandidate(AuthenticationContext, ref objCCandidate);
                            }
                            else
                            {
                                objCCandidate.OrganizationId = CurrentUserSession.OrganizationId;
                                oGCandidate.Status = objMCandidate.UpdateCandidate(AuthenticationContext, ref objCCandidate);
                            }
                        }
                        else
                        {
                            oGCandidate.Status = new CStatus();
                            oGCandidate.Status.Success = false;
                            oGCandidate.Status.StatusDetails = CAppErrorsConstants.NoPermission;
                        }
                    }
                    else
                    {
                        oGCandidate.Status = new CStatus();
                        oGCandidate.Status.Success = false;
                        oGCandidate.Status.StatusDetails = SessionState;
                    }
                }
                else
                {
                    oGCandidate.Status = new CStatus();
                    oGCandidate.Status.Success = false;
                    oGCandidate.Status.StatusDetails = CAppErrorsConstants.ValidationFail;
                }
            }
            catch (Exception ex)
            {
                oGCandidate.Status = new CStatus();
                oGCandidate.Status.Success = false;
                oGCandidate.Status.StatusDetails = ex.Message;
            }
            return Json(oGCandidate);
        }

        [HttpPost]
        public ActionResult GetDetails(int pnId)
        {
            GCandidate objGCandidate = new GCandidate();

            objGCandidate.Status = new CStatus();

            objGCandidate.Candidate = new CCandidate();

            objGCandidate.Candidate.CandidateId = pnId;

            CCandidate objCCandidate = new CCandidate();

            ViewBag.IsDisabled = true;
            try
            {
                //call CheckSession to get session status
                string SessionState = CheckSessionState();

                //IsDisabled checks whether cureently selected row is hardlocked or softlocked by other
                ViewBag.IsDisabled = true;
                ViewBag.IsNew = false;
                //check if session state is ok else return false status to view.
                if (SessionState == CAppConstants.SessionSuccess)
                {
                    MVacancyExpirence objMVacancyExpirence = new MVacancyExpirence();
                    MCandidateSource oMCandidateSource = new MCandidateSource();
                    MDepartment objMDepartment = new MDepartment();

                    // get vacancy expirence list
                    List<CCandidateSource> tempListCandidateSource = new List<CCandidateSource>();
                    objGCandidate.Status = oMCandidateSource.GetCandidateSourceList(AuthenticationContext, CurrentUserSession.OrganizationId, out tempListCandidateSource);
                    objGCandidate.LstCandidateSource = new List<CCandidateSource>();
                    objGCandidate.LstCandidateSource.AddRange(tempListCandidateSource);

                    // get vacancy expirence list
                    List<CVacancyExpirence> tempListVacancyExpirence = new List<CVacancyExpirence>();
                    objGCandidate.Status = objMVacancyExpirence.GetVacancyExpirenceList(AuthenticationContext, CurrentUserSession.OrganizationId, out tempListVacancyExpirence);
                    objGCandidate.LstVacancyExpirence = new List<CVacancyExpirence>();
                    objGCandidate.LstVacancyExpirence.AddRange(tempListVacancyExpirence);

                    // get Department list
                    List<CDepartment> tempListDepartment = new List<CDepartment>();
                    objGCandidate.Status = objMDepartment.GetDepartmentList(AuthenticationContext, CurrentUserSession.OrganizationId, out tempListDepartment);
                    objGCandidate.LstDepartment = new List<CDepartment>();
                    objGCandidate.LstDepartment.AddRange(tempListDepartment);

                    //check if Id param is 0 means new is clicked then set selected row object to new.
                    if (0 == pnId)
                    {
                        if (checkUserPermission(CUserPermissionsConstants.OrganizationCreate))
                        {
                            //here we will append new form to create new organisation
                            ViewBag.IsNew = true;
                            objGCandidate.Status.Success = true;
                            objGCandidate.Status.StatusDetails = CAppConstants.DetailSuccess;
                        }
                        else
                        {
                            objGCandidate.Status.Success = false;
                            objGCandidate.Status.StatusDetails = CAppErrorsConstants.NoPermission;
                        }
                    }
                    else
                    {
                        if (checkUserPermission(CUserPermissionsConstants.OrganizationDetailView))
                        {
                            //here we will append new for detail 
                            MCandidate objMCandidate = new MCandidate();

                            ViewBag.IsNew = false;

                            objCCandidate.CandidateId = objGCandidate.Candidate.CandidateId;

                            objGCandidate.Status = objMCandidate.GetCandidateDetail(AuthenticationContext, ref objCCandidate);

                            //get the different admin names from their id from the application user list
                            objCCandidate.CreatedByName = GetFullName(objCCandidate.CreatedBy);
                            objCCandidate.ModifiedByName = GetFullName(objCCandidate.ModifiedBy);
                            objCCandidate.SoftLockedByName = GetFullName(objCCandidate.SoftLockedBy);
                            objCCandidate.HardLockedByName = GetFullName(objCCandidate.HardLockedBy);


                            if (!CheckLocksByOther(objCCandidate))
                            {
                                ViewBag.IsDisabled = false;
                            }
                            if (objGCandidate.Status.Success == true)
                            {
                                objGCandidate.Candidate = objCCandidate;
                            }
                        }
                        else
                        {
                            objGCandidate.Status = new CStatus();
                            objGCandidate.Status.Success = false;
                            objGCandidate.Status.StatusDetails = CAppErrorsConstants.NoPermission;
                        }
                    }
                }
                else
                {
                    objGCandidate.Status = new CStatus();
                    objGCandidate.Status.Success = false;
                    objGCandidate.Status.StatusDetails = SessionState;
                }
            }
            catch (Exception ex)
            {

                objGCandidate.Status = new CStatus();
                objGCandidate.Status.Success = false;
                objGCandidate.Status.StatusDetails = ex.Message;
            }

            return PartialView("_detail", objGCandidate);
        }

        [HttpPost]
        public ActionResult Delete(string pstrIds)
        {
            GCandidate objGCandidate = new GCandidate();

            objGCandidate.Candidate = new CCandidate();

            objGCandidate.Candidate.CandidateIds = pstrIds;
            try
            {
                //call CheckSession to get session status
                string SessionState = CheckSessionState();

                //IsDisabled checks whether cureently selected row is hardlocked or softlocked by other
                ViewBag.IsDisabled = true;
                ViewBag.IsNew = false;

                //check if session state is ok else return false status to view.
                if (SessionState == CAppConstants.SessionSuccess)
                {
                    //check if Id param is 0 means new is clicked then set selected row object to new.
                    if (pstrIds != "")
                    {
                        if (checkUserPermission(CUserPermissionsConstants.OrganizationDelete))
                        {
                            //code to delete the record
                            MCandidate objMCandidate = new MCandidate();

                            CCandidate objCCandidate = new CCandidate();

                            objCCandidate.CandidateIds = objGCandidate.Candidate.CandidateIds;

                            objGCandidate.Status = objMCandidate.DeleteCandidate(AuthenticationContext, ref objCCandidate);

                            if (objGCandidate.Status.Success == true)
                            {
                                objGCandidate.Candidate = objCCandidate;
                            }
                        }
                        else
                        {
                            objGCandidate.Status = new CStatus();
                            objGCandidate.Status.Success = false;
                            objGCandidate.Status.StatusDetails = CAppErrorsConstants.NoPermission;
                        }
                    }
                    else
                    {
                        objGCandidate.Status = new CStatus();
                        objGCandidate.Status.Success = false;
                        objGCandidate.Status.StatusDetails = CAppErrorsConstants.NotValidRequest;
                    }
                }
                else
                {
                    objGCandidate.Status = new CStatus();
                    objGCandidate.Status.Success = false;
                    objGCandidate.Status.StatusDetails = SessionState;
                }
            }
            catch (Exception ex)
            {

                objGCandidate.Status = new CStatus();
                objGCandidate.Status.Success = false;
                objGCandidate.Status.StatusDetails = ex.Message;
            }

            return Json(objGCandidate.Status);
        }

        [HttpPost]
        public ActionResult GridRefresh(int pnId, string pstrSortOn, string pstrSortType, int pnPageNo, int pnPageSize, string pstrSearch, string pstrSearchOn, int pnOrgId = 1)
        {

            GCandidate objGCandidate = new GCandidate();
            try
            {
                if (pstrSearch == null || pstrSearchOn == null)
                {
                    pstrSearch = "";
                    pstrSearchOn = "";
                }

                //call CheckSession to get session status
                string SessionState = CheckSessionState();

                //check if session state is ok else return false status to view.
                if (SessionState == CAppConstants.SessionSuccess)
                {
                    CCandidate objCCandidate = new CCandidate() { CandidateId = pnId, SortOn = pstrSortOn, SortType = pstrSortType, PageNumber = pnPageNo, RowSize = pnPageSize, Search = pstrSearch, SearchOn = pstrSearchOn, OrganizationId = pnOrgId };


                    //check if current users organization id is 1 then it means it is superUser then need to get all organizations list
                    if (CurrentUserSession.OrganizationId == pnOrgId)
                    {

                        MCandidate objMCandidate = new MCandidate();

                        objGCandidate = objMCandidate.GetCandidateGridList(objCCandidate, AuthenticationContext);

                        if (objGCandidate.LstCandidate != null)
                        {
                            if (objGCandidate.LstCandidate.Count > 0)
                            {
                                objGCandidate.LstCandidate.ForEach(Candidate =>
                                {
                                    Candidate.CreatedByName = GetFullName(Candidate.CreatedBy);
                                    Candidate.ModifiedByName = GetFullName(Candidate.ModifiedBy);
                                    Candidate.SoftLockedByName = GetFullName(Candidate.SoftLockedBy);
                                    Candidate.HardLockedByName = GetFullName(Candidate.HardLockedBy);
                                });
                            }
                        }

                        // if status is true get object of the record to be selected in the list.
                        // first of all we will check the if given record exist in the list.
                        // if given record exist then get the object of that record.
                        // if record not exist in the list then select the first record of the list.
                        if (objGCandidate.Status.Success)
                        {
                            // if status is true get object of the record to be selected in the list.
                            // first of all we will check the if given record exist in the list.
                            // if given record exist then get the object of that record.
                            // if record not exist in the list then select the first record of the list.
                            if (objGCandidate.LstCandidate != null)
                            {
                                CCandidate objSelectedCCandidate = objGCandidate.LstCandidate.Where(m => m.CandidateId == pnId).DefaultIfEmpty(objGCandidate.LstCandidate[0]).First();

                                // check if record is not already hard locked or softlocked
                                if (objSelectedCCandidate.IsSoftLocked == false && objSelectedCCandidate.IsHardLocked == false)
                                {
                                    objSelectedCCandidate.CreatedBy = CurrentUserSession.UserId;
                                    objGCandidate.Status = objMCandidate.SetCandidateSoftLock(AuthenticationContext, objSelectedCCandidate);
                                    if (objGCandidate.Status.Success)
                                    {
                                        // updating the list with softlock details
                                        objGCandidate.LstCandidate.Where(m => m.CandidateId == objSelectedCCandidate.CandidateId).First().IsSoftLocked = true;
                                        objGCandidate.LstCandidate.Where(m => m.CandidateId == objSelectedCCandidate.CandidateId).First().SoftLockedBy = CurrentUserSession.UserId;
                                    }
                                }
                            }


                        }

                        ViewBag.bPagingEnabled = true;
                        ViewBag.bSearchEnabled = true;
                        ViewBag.bNewDeleteEnabled = true;
                        ViewBag.bCopyPasteEnabled = false;
                    }
                    //else get detail for current users organization and show it in grid.
                    else
                    {
                        objCCandidate = new CCandidate() { OrganizationId = CurrentUserSession.OrganizationId };

                        MCandidate objMCandidate = new MCandidate();

                        objGCandidate.Status = objMCandidate.GetCandidateDetail(AuthenticationContext, ref objCCandidate);

                        objGCandidate.LstCandidate.Add(objCCandidate);
                        //set view bag variables for pagging, new, delete and search.
                        ViewBag.bPagingEnabled = false;
                        ViewBag.bSearchEnabled = false;
                        ViewBag.bNewDeleteEnabled = false;
                        ViewBag.bCopyPasteEnabled = false;
                    }

                    // check if status is true
                    if (objGCandidate.Status.Success)
                    {
                        if (objGCandidate.LstCandidate != null)
                        {
                            if (objGCandidate.LstCandidate.Count > 0)
                            {
                                objGCandidate.LstCandidate[0].SortOn = pstrSortOn;
                                objGCandidate.LstCandidate[0].SortType = pstrSortType;
                            }
                        }
                        // set the values of sort on and sort type in the view bag.
                        ViewBag.SortType = pstrSortType;
                        ViewBag.SortOn = pstrSortOn;
                        ViewBag.CurrentUser = CurrentUserSession.UserId;
                    }
                }
                else
                {
                    //set status to false and its detail.
                    objGCandidate.Status = new CStatus();
                    objGCandidate.Status.Success = false;
                    objGCandidate.Status.StatusDetails = SessionState;
                }
            }
            catch (Exception ex)
            {
                // catch the exceptions in any step ,if any 
                //set status to false and its detail as exception message.
                objGCandidate.Status = new CStatus();
                objGCandidate.Status.Success = false;
                objGCandidate.Status.StatusDetails = ex.Message;
            }
            ViewBag.CurrentUser = CurrentUserSession.UserId;
            //check if status is true then return list view(partial view of list) else return object with false status.
            if (objGCandidate.Status.Success)
                return PartialView("_list", objGCandidate);
            else
                return Json(objGCandidate);
        }

        [HttpPost]
        public ActionResult ReleaseSoftLock(int pnId)
        {
            GCandidate objGCandidate = new GCandidate();

            objGCandidate.Candidate = new CCandidate();

            objGCandidate.Candidate.CandidateId = pnId;
            try
            {
                //call CheckSession to get session status
                string SessionState = CheckSessionState();
                //IsDisabled checks whether cureently selected row is hardlocked or softlocked by other
                ViewBag.IsDisabled = true;
                ViewBag.IsNew = false;
                //check if session state is ok else return false status to view.
                if (SessionState == CAppConstants.SessionSuccess)
                {

                    //check if Id param is 0 means new is clicked then set selected row object to new.
                    if (0 == pnId)
                    {
                        if (checkUserPermission(CUserPermissionsConstants.OrganizationUpdate))
                        {
                            //here we will append new form to create new organisation
                            ViewBag.IsNew = true;
                            objGCandidate.Status.Success = true;
                        }
                        else
                        {
                            objGCandidate.Status.Success = false;
                            objGCandidate.Status.StatusDetails = CAppErrorsConstants.NoPermission;
                        }
                    }
                    else
                    {
                        MCandidate objMCandidate = new MCandidate();
                        objGCandidate.Candidate.CreatedBy = CurrentUserSession.UserId;
                        objGCandidate.Status = objMCandidate.ReleaseCandidateSoftLock(AuthenticationContext, objGCandidate.Candidate);
                    }
                }
                else
                {
                    objGCandidate.Status = new CStatus();
                    objGCandidate.Status.Success = false;
                    objGCandidate.Status.StatusDetails = SessionState;
                }
            }
            catch (Exception ex)
            {

                objGCandidate.Status = new CStatus();
                objGCandidate.Status.Success = false;
                objGCandidate.Status.StatusDetails = ex.Message;
            }

            return Json(objGCandidate.Status);
        }

        [HttpPost]
        public ActionResult SetHardLock(int pnId)
        {
            GCandidate objGCandidate = new GCandidate();

            objGCandidate.Candidate = new CCandidate();

            objGCandidate.Candidate.CandidateId = pnId;
            try
            {
                //call CheckSession to get session status
                string SessionState = CheckSessionState();
                //IsDisabled checks whether cureently selected row is hardlocked or softlocked by other
                ViewBag.IsDisabled = true;
                ViewBag.IsNew = false;
                //check if session state is ok else return false status to view.
                if (SessionState == CAppConstants.SessionSuccess)
                {
                    MCandidate objMCandidate = new MCandidate();
                    objGCandidate.Candidate.CreatedBy = CurrentUserSession.UserId;
                    objGCandidate.Status = objMCandidate.SetCandidateHardLock(AuthenticationContext, objGCandidate.Candidate);
                }
                else
                {
                    objGCandidate.Status = new CStatus();
                    objGCandidate.Status.Success = false;
                    objGCandidate.Status.StatusDetails = SessionState;
                }
            }
            catch (Exception ex)
            {

                objGCandidate.Status = new CStatus();
                objGCandidate.Status.Success = false;
                objGCandidate.Status.StatusDetails = ex.Message;
            }
            return Json(objGCandidate.Status);
        }

        [HttpPost]
        public ActionResult ReleaseHardLock(int pnId)
        {
            GCandidate objGCandidate = new GCandidate();

            objGCandidate.Candidate = new CCandidate();

            objGCandidate.Candidate.CandidateId = pnId;
            try
            {
                //call CheckSession to get session status
                string SessionState = CheckSessionState();
                //IsDisabled checks whether cureently selected row is hardlocked or softlocked by other
                ViewBag.IsDisabled = true;
                ViewBag.IsNew = false;
                //check if session state is ok else return false status to view.
                if (SessionState == CAppConstants.SessionSuccess)
                {
                    MCandidate objMCandidate = new MCandidate();
                    objGCandidate.Candidate.CreatedBy = CurrentUserSession.UserId;
                    objGCandidate.Status = objMCandidate.ReleaseCandidateHardLock(AuthenticationContext, objGCandidate.Candidate);
                }
                else
                {
                    objGCandidate.Status = new CStatus();
                    objGCandidate.Status.Success = false;
                    objGCandidate.Status.StatusDetails = SessionState;
                }
            }
            catch (Exception ex)
            {

                objGCandidate.Status = new CStatus();
                objGCandidate.Status.Success = false;
                objGCandidate.Status.StatusDetails = ex.Message;
            }

            return Json(objGCandidate.Status);
        }
    }
}
